import * as types from '../actionTypes/todos'

const initialState = [
  { id: 1, text: '吃饭', done: false },
  { id: 2, text: '学习', done: false },
  { id: 3, text: '睡觉', done: true }
]

const todos = (state = initialState, action) => {
  switch (action.type) {
    // 删除任务
    case types.DEL_TODO:
      return state.filter(item => item.id !== action.payload)
    // 切换状态
    case types.TOGGLE_DONE:
      return state.map(item => {
        if (item.id === action.payload.id) {
          return { ...item, done: action.payload.done }
        } else {
          return item
        }
      })
    // 添加任务
    case types.ADD_TODO:
      // 追加最后，id就取最后的任务的ID+1即可
      const id = state.length === 0 ? 1 : state[state.length - 1].id + 1
      return [...state, {
        id,
        text: action.payload,
        done: false
      }]
    // 全选  
    case types.TOGGLE_ALL:
      return state.map(item => ({ ...item, done: action.payload }))
    // 清空完成的  
    case types.CLEAR_DONE:
      return state.filter(item => !item.done)
    // 修改任务
    case types.UPDATE_TODO:
      return state.map(item => {
        if (item.id === action.payload.id) {
          return { ...item, text: action.payload.text }
        }
        return item
      })
    default:
      return state
  }
}

export default todos